﻿using CSLC.WeChat.PublicAccount;
using CSLC.WeChat.PublicLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace CSLC.WeChat.UI.MVC
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : Spring.Web.Mvc.SpringMvcApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            #region 注册公众号
            // 在应用程序启动时运行的代码
            //填写默认的SQL SERVER数据库连接字符串
            DataAccess.connectionString = ConfigurationManager.AppSettings["SQLConnectionStr"];
            //加入测试公众号
            AccountInfo info = new AccountInfo(ConfigurationManager.AppSettings["CSLCPublicUserName"], ConfigurationManager.AppSettings["CSLCPublicAppId"],ConfigurationManager.AppSettings["CSLCPublicAppSecret"],
                ConfigurationManager.AppSettings["CSLCPublicToken"],ConfigurationManager.AppSettings["CSLCPublicEncodingAESKey"], ConfigurationManager.AppSettings["CSLCPublicCaption"]);            
            AccountInfoCollection.SetAccountInfo(info);
            //如果针对多个公众号服务，那么可以多次SetAccountInfo
            #endregion
        }

        protected void Application_Error()
        {
            if (Server.GetLastError() == null)
                return;
            Exception exp = Server.GetLastError().GetBaseException();
            HandleException(exp);
            if (exp.InnerException != null)
                HandleException(exp.InnerException);
        }
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="e"></param>
        private void HandleException(Exception e)
        {
            string err = string.Format("捕获未处理的异常。\r\n出错页面：{0}\r\n出错方法：{1}\r\n错误源：{2}\r\n错误提示：{3}\r\n堆栈：{4}",
                Request != null ? Request.RawUrl.ToString() : "", e.TargetSite, e.Source, e.Message, e.StackTrace);
            CSLC.WeChat.PublicAccount.Message message = new Message(MessageType.Exception, err);
            Message.Insert(message);
        }
    }
}